package com.fa4j.common.web.util;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;

public class CookieUtil {

    public static void set(String tokenName, String tokenValue, boolean httpOnly) {
        Cookie cookie = new Cookie(tokenName, tokenValue);
        cookie.setHttpOnly(httpOnly);
        if (RequestContextHolder.currentRequestAttributes() instanceof ServletRequestAttributes requestAttributes) {
            HttpServletResponse response = requestAttributes.getResponse();
            if (response != null) {
                response.addCookie(cookie);
            }
        }
    }

    public static Optional<String> get(String tokenName) {
        if (RequestContextHolder.currentRequestAttributes() instanceof ServletRequestAttributes requestAttributes) {
            if (requestAttributes.getRequest().getCookies() != null) {
                for (Cookie cookie : requestAttributes.getRequest().getCookies()) {
                    if (tokenName.equals(cookie.getName())) {
                        return Optional.ofNullable(cookie.getValue());
                    }
                }
            }
        }
        return Optional.empty();
    }
}
